package com.example.maple.ccsclient.presenter;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.text.Layout;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.example.maple.ccsclient.R;
import com.example.maple.ccsclient.adapter.GroupAdapter;
import com.example.maple.ccsclient.app.InputActivity;
import com.example.maple.ccsclient.app.LackActivity;
import com.example.maple.ccsclient.app.ReportActivity;
import com.example.maple.ccsclient.app.SettingActivity;
import com.example.maple.ccsclient.interfaces.IPreviewView;
import com.example.maple.ccsclient.model.AllDataInfoUtils;
import com.example.maple.ccsclient.model.DataModel;
import com.example.maple.ccsclient.model.ISendData;
import com.example.maple.ccsclient.model.PicModel;
import com.example.maple.ccsclient.utils.CloseUtils;
import com.example.maple.ccsclient.utils.SharedPreferencesUtils;
import com.example.maple.ccsclient.utils.SharedUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadFactory;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * Created by maple on 2016/6/21.
 */
public class HomePagePresenter {

	private final View view;
	private final ListView lv_group;

	private List<String> groups;
	GroupAdapter mGroupAdapter = null;
	/*
		* 这个Presenter里面是和UI相关的，所以耗时任务最好开启线程
		* */
	private PopupWindow mPopupWindow = null;
	IPreviewView mIPreviewView;
	Context mContext = null;
	AllDataInfoUtils mAllDataInfoUtils = null;
	LayoutInflater layoutInflater;

	public HomePagePresenter(IPreviewView iPreviewView, Context context) {

		mContext = context;
		mIPreviewView = iPreviewView;
		mAllDataInfoUtils = new AllDataInfoUtils(mContext);
		groups = new ArrayList<>();
		groups.add("分享");
		groups.add("缺字统计");
		groups.add("文章查询");
		groups.add("设置");
		mGroupAdapter = new GroupAdapter(mContext, R.layout.group_item_view, groups);
		layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);


		view = layoutInflater.inflate(R.layout.group_list, null);
		lv_group = (ListView) view.findViewById(R.id.lvGroup);
		lv_group.setAdapter(mGroupAdapter);
		lv_group.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				String info = (String) parent.getItemAtPosition(position);
				switch (info) {
					case "分享": {
						if (mPopupWindow != null) {
							mPopupWindow.dismiss();
							SharedUtils.showShare(mContext,"分享");
						}
						break;
					}
					case "缺字统计": {
						if (mPopupWindow != null) {
							mPopupWindow.dismiss();
						}
						LackActivity.startAction(mContext, "缺字统计");
						break;
					}
					case "文章查询": {
						if (mPopupWindow != null) {
							mPopupWindow.dismiss();
						}
						InputActivity.startAction(mContext, "文章查询");

						break;
					}
					case "设置": {
						if (mPopupWindow != null) {
							mPopupWindow.dismiss();
							SettingActivity.startAction(mContext);
						}
						break;
					}
				}
			}
		});


	}


	//刷新
	public void refresh() {

		mIPreviewView.startAnimation();
		getFamousVerse();

	}

	//获取名言诗句
	public void getFamousVerse() {

		MyAsyncTask task = new MyAsyncTask();
		task.execute();

	}

	//显示图片
	public void showFamousVersePic(final String s1, final String s2) {
		mAllDataInfoUtils.getCharPic(true,String.format("%s%s", s1, s2), new ISendData() {
			@Override
			public void sendData(Object o) {
				DataModel<Object> info = (DataModel<Object>) o;

				//当获取完网络数据时候，停止动画
				mIPreviewView.stopAnimation();

				if (info.getStatus() == 1) {
					mIPreviewView.showFamousVersePic((List<PicModel>) info.getData());
					mIPreviewView.showFamousVerse(s1, s2);
					SharedPreferencesUtils.setFirstData(mContext,String.format("%s#%s#%s",s1,s2,info.getInfo()));

				} else if (info.getStatus() == -100) {
					//如果使网络失败，就加载以前的
					//显示错误信息  并且隐藏加载符号
					mIPreviewView.showDialog(info.getInfo());
					String firstData = SharedPreferencesUtils.getFirstData(mContext);
					if (!TextUtils.isEmpty(firstData)) {
						String[] data = firstData.split("#");
						if (data.length == 3) {
							mIPreviewView.showFamousVerse(data[0], data[1]);
							Gson gson = new Gson();
							DataModel<List<PicModel>> dataModel = gson.fromJson(data[2], new TypeToken<DataModel<List<PicModel>>>() {
							}.getType());
							mIPreviewView.showFamousVersePic(dataModel.getData());
						}
					}

				} else {
					//显示错误信息  并且隐藏加载符号
					mIPreviewView.showDialog(info.getInfo());
				}
			}
		});

	}

	//PopupWindow
	public void showWindow(View v, int width, int height) {
		if (mPopupWindow == null) {
			mPopupWindow = new PopupWindow(view, width / 2, WindowManager.LayoutParams.WRAP_CONTENT);
		}

		// 使其聚集
		mPopupWindow.setFocusable(true);
		// 设置允许在外点击消失
		mPopupWindow.setOutsideTouchable(true);

		// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
		mPopupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
		mPopupWindow.showAsDropDown(v, width / 2, 0);
	}

	//隐藏PopupWindow
	public void hiddenWindows() {
		if (mPopupWindow != null) {
			mPopupWindow.dismiss();
		}
	}

	//PopupWindow是否显示
	public boolean windowIsShowing() {

		if (null != mPopupWindow && mPopupWindow.isShowing()) {
			return true;
		} else {
			return false;
		}
	}

	public class MyAsyncTask extends AsyncTask<Nullable, Nullable, String[]> {

		@Override
		protected String[] doInBackground(Nullable... params) {

/*
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}*/

			String[] info = null;
			//产生随机数，用于获取两个名言诗句
			Random random = new Random();
			//首先产生第一个随机数
			int one = random.nextInt(5668) + 1;
			int two;
			//这里用死循环产生第二个不同于第一个的数
			while (true) {
				two = random.nextInt(5668) + 1;
				if (one != two) {
					break;
				}
			}
			InputStream stream = null;
			InputStreamReader inputStreamReader = null;
			BufferedReader bufferedReader = null;
			try {
				stream = ((Context) mIPreviewView).getAssets().open("StringInfo.txt");
				inputStreamReader = new InputStreamReader(stream);
				bufferedReader = new BufferedReader(inputStreamReader);
				int count = 0;
				int max = one > two ? one : two;
				String oneStr = null, twoStr = null, temp;
				while (null != (temp = bufferedReader.readLine()) && count <= max) {
					count++;
					if (count == one) {
						oneStr = temp;
					} else if (count == two) {
						twoStr = temp;
					}
				}
				//显示名言诗句
				info = new String[2];
				info[0] = oneStr;
				info[1] = twoStr;
				return info;
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				CloseUtils.closeQuietly(stream);
				CloseUtils.closeQuietly(inputStreamReader);
			}
			return null;
		}


		@Override
		protected void onPostExecute(String[] strings) {
			if (null != strings) {

				//显示图片
				showFamousVersePic(strings[0], strings[1]);
			}


		}
	}
}
